import urls from '/util/urls'
import request from '/util/request'
import { parseTime, isWorkerRole, alert } from '/util/utils'
import moment from 'moment'
const app = getApp()

Page({
  data: {
    form: {
      id: '',
      /** 日报日期 */
      dailyReportDate: parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00:00',
      /** 单位编码 */
      unitCode: '',
      /** 单位名称 */
      unitName: '',
      /** 运维小组编码 */
      operationGroupCode: '',
      /** 运维小组名称 */
      operationGroupName: '',
      /** 事件请求人/处室 */
      eventRequester: '',
      /** 响应方式 */
      responseMethod: '',
      responseMethodText: '',
      /** 事件处理地点 */
      incidentLocation: '',
      /** 事件处理人编码 */
      incidentUserCode: '',
      /** 事件处理人名称 */
      incidentUserName: '',
      /** 服务类型编码 */
      serviceTypeCode: '',
      /** 服务类型名称 */
      serviceTypeName: '',
      /** 服务属性编码 */
      serviceAttributesCode: '',
      /** 服务属性名称 */
      serviceAttributesName: '',
      /** 服务开始时间 */
      serviceStartTime: '',
      /** 服务结束时间 */
      serviceEndTime: '',
      /** 事件等级 */
      eventLevel: '',
      eventLevelText: '',
      /** 工作总时长 */
      totalWorkingHours: 0,
      /** 服务单号 */
      trackingNo: '',
      /** 工作内容 */
      jobContent: '',
      /** 备注 */
      remarks: '',
      /** 单位的活性 */
      unitDisabled:true
    },
    availableResponseMethods: [],
    availableServiceTypes: [],
    availableEventLevels: [],
    availableServiceAttributesCodes: [],
    focus: false
  },
  onLoad(query) {
    this.data.form.id = query.id
    request.login(this.init.bind(this))
  },
  init() {
    const that = this
    // this.getMyInfo()
    // this.getMyInstitutionInfo()
    if(that.data.form.id > -1) {
      request.get(urls.workDailyDetailUrl(that.data.form.id), info => {
        info.serviceStartTime = parseTime(info.serviceStartTime, '{h}:{i}')
        info.serviceEndTime = parseTime(info.serviceEndTime, '{h}:{i}')
        that.setData({
          form: info
        })
        if(info.serviceTypeCode) {
           request.get(urls.dictUrl(info.serviceTypeCode), function(data){
            that.setData({
              availableServiceAttributesCodes: data
            })
          })
        }
      })
    }
    request.get(urls.responseMethodDictUrl(), function(data){
      that.setData({
        availableResponseMethods: data
      })
    })
    request.get(urls.worktypeDictUrl(), function(data){
      that.setData({
        availableServiceTypes: data
      })
    })
    request.get(urls.eventgradeDictUrl(), function(data){
      that.setData({
        availableEventLevels: data
      })
    })
    this.setData({
      'form.unitCode': app.globalData.instituteInfo.defaultInstituteCode,
      'form.unitName': app.globalData.instituteInfo.defaultInstituteName,
      'form.operationGroupCode': app.globalData.instituteInfo.groupCode,
      'form.operationGroupName': app.globalData.instituteInfo.groupName,
      'form.incidentUserCode': app.globalData.userInfo.username,
      'form.incidentUserName': app.globalData.userInfo.name
    })
  },
  onItemInput(e) {
    this.setData({
      [e.target.dataset.field]: e.detail.value,
    });
  },
  onClear(e) {
    this.setData({
      [e.target.dataset.field]: '',
    });
  },
  onJobContentInput(e) {
    this.setData({
      'form.jobContent': e.detail.value,
    });
  },
  onUnitCodePickerTap() {
    // 一线工程师只能填写自己单位下面的日报
    if(isWorkerRole() === true){
      return ;
    }
    const items = app.globalData.instituteInfo.institutions.map(item => item.name)
    my.showActionSheet({
      title: '选择单位',
      items: items,
      cancelButtonText: '取消',
      success: (res) => {
        const i = app.globalData.instituteInfo.institutions[res.index]
        if(i) {
          this.setData({
            'form.unitCode': i.code,
            'form.unitName': i.name,
          });
        }
      },
    });
  },
  onResponseMethodPickerTap() {
    const items = this.data.availableResponseMethods.map(item => item.text)
    my.showActionSheet({
      title: '选择响应方式',
      items: items,
      cancelButtonText: '取消',
      success: (res) => {
        const i = this.data.availableResponseMethods[res.index]
        if(i) {
          this.setData({
            'form.responseMethod': i.code,
            'form.responseMethodText': i.text,
          });
        }
      },
    });
  },
  onServiceTypePickerTap() {
    const that = this
    const items = this.data.availableServiceTypes.map(item => item.text)
    my.showActionSheet({
      title: '选择服务类型',
      items: items,
      cancelButtonText: '取消',
      success: (res) => {
        const i = this.data.availableServiceTypes[res.index]
        if(i) {
          this.setData({
            'form.serviceTypeCode': i.code,
            'form.serviceTypeName': i.text,
          });

          request.get(urls.dictUrl(i.code), function(data){
            that.setData({
              'form.serviceAttributesCode': '',
              'form.serviceAttributesName': '',
              availableServiceAttributesCodes: data
            })
          })
        }
      },
    });
  },
  onServiceAttributesPickerTap() {
    const items = this.data.availableServiceAttributesCodes.map(item => item.text)
    my.showActionSheet({
      title: '选择服务属性',
      items: items,
      cancelButtonText: '取消',
      success: (res) => {
        const i = this.data.availableServiceAttributesCodes[res.index]
        if(i) {
          this.setData({
            'form.serviceAttributesCode': i.code,
            'form.serviceAttributesName': i.text,
          });
        }
      },
    });
  },
  onEventLevelPickerTap() {
    const items = this.data.availableEventLevels.map(item => item.text)
    my.showActionSheet({
      title: '选择事件等级',
      items: items,
      cancelButtonText: '取消',
      success: (res) => {
        const i = this.data.availableEventLevels[res.index]
        if(i) {
          this.setData({
            'form.eventLevel': i.code,
            'form.eventLevelText': i.text,
          });
        }
      },
    });
  },
  onStartTimeFocus() {
    const that = this
    dd.datePicker({
      format: 'HH:mm',
      success: (res) => {
        that.setData({
          'form.serviceStartTime': res.date
        })
      },
      complete: () => {
        setTimeout(() => {
          that.setData({
            focus: true
          })
        },100)
        
      }
    })
  },
  onStartTimeInput(e) {
    this.setData({
      'form.serviceStartTime': e.detail.value
    })
  },
  onEndTimeFocus() {
    const that = this
    dd.datePicker({
      format: 'HH:mm',
      success: (res) => {
        that.setData({
          'form.serviceEndTime': res.date
        });
      },
      complete: () => {
        setTimeout(() => {
          that.setData({
            focus: true
          })
        },100)
      }
    })
  },
  onEndTimeInput(e) {
    this.setData({
      'form.serviceEndTime': e.detail.value
    })
  },
  validData(formData) {

    if(!formData.unitCode) {
      alert('请选择单位')
      return false
    }
    if(!/^[0-9]{2}:[0-9]{2}$/.test(formData.serviceStartTime)) {
      alert('开始时间格式错误')
      return false
    }
    //if(!formData.serviceEndTime) {
    if(!/^[0-9]{2}:[0-9]{2}$/.test(formData.serviceEndTime)) {
      alert('结束时间格式错误')
      return false
    }
    if(moment(moment().format('YYYY-MM-DD ') + formData.serviceEndTime).isSameOrBefore(moment().format('YYYY-MM-DD ') + formData.serviceStartTime)) {
      alert('结束时间不能超过开始时间')
      return false
    }
    if(!formData.jobContent) {
      alert('请输入工作内容')
      return false
    }
    return true
  },
  onSubmit() {
    this.submit()
  },
  onContinue() {
    this.submit(true)
  },
  submit(continueWrite) {
    const that = this
    const formData = this.data.form
    if(!that.validData(formData)) {
      return
    }
    const todayDateStr = parseTime(new Date(), '{y}-{m}-{d}')
    formData.serviceStartTime = todayDateStr + ' ' + formData.serviceStartTime + ':00'
    formData.serviceEndTime = todayDateStr + ' ' + formData.serviceEndTime + ':00'
    dd.showLoading({
      content: '提交中...',
    })
    if(formData.id > -1) {
      request.put(urls.workDailyDetailUrl(formData.id), formData, () => {
        that.submitSuccess(continueWrite)
      }, () => {
        that.submitFailure()
      })
    } else {
      request.post(urls.workDailyUrl(), formData, () => {
        that.submitSuccess(continueWrite)
      }, () => {
        that.submitFailure()
      })
    }
  },
  submitSuccess(continueWrite) {
    dd.hideLoading()
    //dd.alert({content: '提交成功'})
    dd.showToast({
      type: 'success',
      content: '提交成功',
      duration: 1000,
      success: () => {
        if(continueWrite) {
          dd.redirectTo({
            url: '/pages/writedaily/writedaily'
          })
        } else {
          dd.redirectTo({
            url: '/pages/index/index'
          })
        }
      },
    })
  },
  submitFailure() {
    dd.hideLoading()
    dd.showToast({
      type: 'fail',
      content: '提交失败',
      duration: 1000,
    })
  }
});
